package com.bungarus.rm.controller;

import com.bungarus.error.BungarusError;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.IOException;

/**
 * Created by tang on 2018/12/14.
 */
public abstract class BungarusController {

    @ExceptionHandler({IllegalArgumentException.class, Exception.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BungarusError dealException(Throwable e) {
        BungarusError error = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            error = mapper.readValue(e.getMessage(), BungarusError.class);
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }
        if(null == error) {
            error = BungarusError.newBuilder()
                    .code(HttpStatus.BAD_REQUEST.value())
                    .message(HttpResponseStatus.BAD_REQUEST.getReasonPhrase())
                    .build();
        }
        return error;
    }
}
